package cmgine.com.testqq.http;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import cmgine.com.testqq.adapter.MessageAdapter;
import cmgine.com.testqq.bean.UserInfoWrapper;

/**
 * Created by apple on 12/24/15.
 */
public class HttpDownloader extends AsyncTask<String, Void, String> {

    private URL url;
    private HttpURLConnection httpURLConnection;
    private String result;
    private Context context;
    private ImageView imageView;
    private ListView listView;

    public HttpDownloader(Context context, ListView listView) {
        this.context = context;
        this.listView = listView;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getResult() {
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("main", result);
        try {
            Gson gson = new Gson();
            UserInfoWrapper wrapper = new Gson().fromJson(result, UserInfoWrapper.class);
            MessageAdapter adapter = new MessageAdapter(context, wrapper.userInfo);
            listView.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String doInBackground(String... params) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader buffer = null;
        try {
            url = new URL("http://192.168.0.101:8080/users/users.json");
            httpURLConnection = (HttpURLConnection)url.openConnection();
            buffer = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            while((line = buffer.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                buffer.close();
            } catch(Exception e2) {
                e2.printStackTrace();
            }
        }
        return sb.toString();
    }
}
